<template>
  <el-container class="wh100 of-hide">
    <el-main class="p0 login">
      <el-card class="p0">
        <div class="pl10 pr10">
          <h1 class="logo w100 center"><div class="lo-img login-logo mt10 mb10 mr5" />蓝羽后台管理系统</h1>
          <el-divider class="gray"><i class="iconfont icon-web mr5 gray" />web登录</el-divider>
          <el-form ref="par" :model="par" :rules="rules" label-width="0" class="login-form">
            <el-form-item label="" prop="username">
              <el-input v-model="par.username" type="text" autocomplete="off" placeholder="请输入账号" @keyup.enter.native="sign">
                <i slot="prefix" class="el-icon-user el-input__icon input-icon" />
              </el-input>
            </el-form-item>
            <el-form-item label="" prop="password">
              <el-input v-model="par.password" type="password" autocomplete="off" placeholder="请输入密码" @keyup.enter.native="sign">
                <i slot="prefix" class="el-icon-lock el-input__icon input-icon" />
              </el-input>
            </el-form-item>
            <el-form-item v-if="captchaEnabled" prop="captcha">
              <el-input
                v-model="par.code"
                auto-complete="off"
                placeholder="验证码"
                style="width: 63%"
                @keyup.enter.native="sign"
              >
                <i slot="prefix" class="el-icon-lock el-input__icon input-icon" />
              </el-input>
              <div class="login-code">
                <img :src="codeUrl" class="login-code-img" @click="getCode">
              </div>
            </el-form-item>
          </el-form>
          <el-button :loading="loging" class="w100" type="primary" @click="sign">登录</el-button>
          <el-divider><i class="iconfont icon-wechat point" /></el-divider>
        </div>
      </el-card>
    </el-main>
    <el-footer class="center gray" style="font-size: 14px">
      Copyright © 2022 by zhoulang1996@qq.com 蓝羽 鄂ICP备2021022601号-2
    </el-footer>
  </el-container>
</template>

<script>
import { validator } from '@/utils/form'
import { getPubKey } from '@/api/sys'
import { captchaImage } from '@/api/login'

export default {
  name: 'Login',
  components: {},
  data() {
    return {
      loging: false,
      codeUrl: '',
      pubKey: '',
      redirect: null,
      captchaEnabled: false,
      otherQuery: {},
      par: {
        username: 'ql.wu',
        password: '111111',
        uuid: '',
        code: ''
      }
    }
  },
  computed: {
    rules() {
      return {
        username: [
          { validator: validator('notBlank'), message: '请输入账号', trigger: ['blur', 'change'] }
        ],
        password: [
          { validator: validator('notBlank'), message: '请输入密码', trigger: ['blur', 'change'] }
        ],
        captcha: [
          { validator: validator(this.checkCaptcha), message: '请输入验证码', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    this.getCode()
  },
  mounted() {
    const that = this
    document.onkeydown = function(e) {
      const key = window.event ? e.keyCode : e.which
      if (key === 13) {
        that.sign()
      }
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    getCode() {
      this.loging = true
      captchaImage().then(res => {
        this.loging = false
        // console.log(res)
        this.captchaEnabled = res.captchaEnabled !== false
        if (this.captchaEnabled) {
          this.codeUrl = 'data:image/gif;base64,' + res.img
          this.par.uuid = res.uuid
        }
      }).catch(e => {
        this.loging = false
        this.$message.error('验证码加载失败')
      })
    },
    sign() {
      this.$refs['par'].validate((valid) => {
        if (valid && !this.loging) {
          this.loging = true
          if (this.pubKey) {
            this.doLogin()
          } else {
            getPubKey().then((r) => {
              this.pubKey = r
              this.doLogin()
            })
          }
        }
      })
    },
    doLogin() {
      const par = this.$util.copy(this.par)
      par.password = this.$util.rsa(this.pubKey, par.password)
      //console.log(par)
      this.loging = true
      this.$store.dispatch("Login", par).then((e) => {
        const d = e.data
        if (d.appToken) {
          const u = d.userInfo
          this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
          this.$notify({
            title: '登录成功',
            type: 'success',
            message: (u.realName || u.username) + '，欢迎回来',
            duration: 5 * 1000
          })
        }else{
          this.loging = false
        }
      }).catch(() => {
        this.loging = false;
        if (this.captchaEnabled) {
          this.getCode()
        }
      });

    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
    checkCaptcha() {
      return !this.captchaEnabled || this.$util.isNotBlank(this.par.code)
    }
  }
}
</script>

<style scoped rel="stylesheet/scss" lang="scss">

.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/image/1.jpg");
  background-size: cover;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  text-align: left;
  width: 400px;
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 38px;
}

</style>

